/**
 * Copyright 2016-2018 mobaas.com
 */
package com.mobaas.devops.vcs;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;

import com.mobaas.devops.VcsProvider;
import com.mobaas.devops.model.VcsDayStat;
import com.mobaas.devops.model.VcsMonthStat;

/**
 * Git访问实现
 * @author billy zhang
 *
 */
public class GitProviderImpl implements VcsProvider {

	private String repoUrl;
	private String username;
	private String password;
	private String localRepoPath;
	
	public void init(Map<String, Object> config) {
		
		this.repoUrl = (String)config.get("repoUrl");
		this.username = (String)config.get("username");
		this.password = (String)config.get("password");
		this.localRepoPath = (String)config.get("localRepoPath");
	}

	@Override
	public List<VcsDayStat> getLastDayStatList() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<VcsMonthStat> getLastMonthStatList() {
		// TODO Auto-generated method stub
		return null;
	}

	 /**
     * 创建本地新仓库
     * @param repoPath 仓库地址 D:/workspace/TestGitRepository
     * @return
     * @throws IOException
     */
    private Repository createNewRepository(String repoPath) throws IOException {
        File localPath = new File(repoPath);
        // create the directory
        Repository repository = FileRepositoryBuilder.create(new File(localPath, ".git"));
        repository.create();
        return repository;
    }
    /**
     * 创建仓库，仅需要执行一次
     */
    private boolean setupRepository(){
    	boolean setupRepositoryFlag=true;
    	try {
            //设置远程服务器上的用户名和密码
            if(isEmpty(username) || isEmpty(password)){
            	Git git =Git.cloneRepository().setURI(repoUrl) //设置远程URI
        				.setBranch("master")   //设置clone下来的分支,默认master
        				.setDirectory(new File(localRepoPath))  //设置下载存放路径
        				.call();
            }else{
                UsernamePasswordCredentialsProvider provider =new UsernamePasswordCredentialsProvider(username, password);
            	Git git =Git.cloneRepository().setURI(repoUrl) //设置远程URI
        				.setBranch("master")   //设置clone下来的分支,默认master
        				.setDirectory(new File(localRepoPath))  //设置下载存放路径
        				.setCredentialsProvider(provider) //设置权限验证
        				.call();
            }
		} catch (Exception e) {
			e.printStackTrace();
			setupRepositoryFlag=false;
		}
    		return setupRepositoryFlag;
    }

    private boolean isEmpty(String str) {
    		return str == null || str.length() == 0;
    }
}
